package com.xiaoyun.execption;

import com.xiaoyun.utils.XYJSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.core.MethodParameter;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class CustomExceptionHandler {

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public XYJSONResult handlerMaxUploadFile(MaxUploadSizeExceededException e) {
        return XYJSONResult.errorMsg("文件大小不能超过500k,请压缩图片大小或者降低质量再上传");
    }

    @ExceptionHandler(BindException.class)
    public XYJSONResult BindException(BindException e) {
        Map<String, String> map = e.getBindingResult().getFieldErrors().stream()
                .collect(Collectors.toMap(FieldError::getField, DefaultMessageSourceResolvable::getDefaultMessage));
        return XYJSONResult.errorMap(map);
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public XYJSONResult MethodArgumentNotValidException(MethodArgumentNotValidException e) {

        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        if (fieldErrors == null || fieldErrors.size() < 1) {
            List<ObjectError> globalErrors = e.getBindingResult().getGlobalErrors();
            StringBuilder sb = new StringBuilder();
            globalErrors.forEach(ge ->
                    sb.append(ge.getDefaultMessage()).append(",")
            );
            sb.deleteCharAt(sb.length() - 1);
            return XYJSONResult.errorMsg(sb.toString());
        } else {
            Map<String, String> errMap = new HashMap<>();
            for (FieldError fieldError : fieldErrors) {
                String defaultMessage = fieldError.getDefaultMessage();
                String field = fieldError.getField();
                errMap.put(field, defaultMessage);
            }
            return XYJSONResult.errorMap(errMap);
        }
    }

}
